<?php

/**
 * Tags Class
 *
 * Used to manage all tags for a page.
 */

require_once("tag.php");

class folio_tags {

//////////////////
//              //
//  SQL Layer   //
//              //
//////////////////

    /**
     * Used to return pages with similar tags
     * @param array $tags An array of pages.
     * @param folio_page $exclude_page A page to not show
     * @param int $limit The maximum number of pages to show
     * @param int $start Paging
     * @return array An array of folio_pages
     */
    public function SelectWhereSimilar( $tags,
                                        $exclude_page = false,
                                        $limit = -1,
                                        $start = 0 ) {
        global $CFG;
        if ( count($tags) == 0 ) return false;

        $p = array();
        $where = '';
        foreach( $tags as $t ) {
            if( get_class($t) == 'folio_tag') {
                // An array of folio_tags
                $where .= "'{$t->tag}',";
            } else {
                // Just an array of strings.
                $where .= "'{$t}',";
            }
        }
        $where = substr($where, 0, strlen($where)-1);

        // Limit with one has been passed.
        if( $limit = -1) {
            $limit = "";
        } else {
            $limit =  "LIMIT {$start}, {$limit}";
        }

        // Add permissions
        // This is done so that later, when I remove the below function,
        //      I'll see this & fix the permissions in this function.
        $accesslevel = ' AND accesslevel in ("' . implode( '","',
            folio_page_permission::permissionlist($_SESSION['userid']) ) . '")';

        // Use a Inner join to filter out tags that weren't deleted along with
        //      deleted pages.
        $sql = "select t.ref, count(*) as c from {$CFG->prefix}tags t " .
                "INNER JOIN {$CFG->prefix}folio_page p ON " .
                "t.ref = p.page_ident AND " .
                "p.newest = 1 " .
                "INNER JOIN {$CFG->prefix}folio_page_security s ON " .
                "p.security_ident = s.security_ident " .
                "WHERE t.tagtype='page' AND t.tag IN ({$where}) " .
                " AND s.accesslevel <> 'private' " .
                "GROUP BY t.ref order by count(*) " .
                $limit;

        $pages = recordset_to_array( get_recordset_sql( $sql ));

        if( !!$pages ) {
            foreach( $pages as $page ) {
                $p[$page->ref] = folio_page::SelectWherePageIdent( $page->ref );
            }
        }
        return $p;

    }

    /**
     * Use to choose a row at a time for the SelectWhereSimilar
     * I know it's inefficient, but since we'll be upgrading to a new
     * permission system with Elgg 1.0, it's simpler.
     */
    private function SelectWhereSimilar_private(
        $sql
    ) {

    }

    /**
     * Load tags from db for the passed page.
     *
     * @param folio_page $page_ident The page to load tags for
     * @return array
     */
    function SelectWherePageIdent( $page_ident ) {
        global $CFG;

        $tags = recordset_to_array( get_recordset_sql( "SELECT ident, tag FROM " . $CFG->prefix . "tags ".
            "WHERE tagtype='page' AND ref = $page_ident ORDER BY tag" ) );

        $a = array();

        if( !!$tags ) {
            foreach( $tags as $tag ) {
                $a[] = new folio_tag( $tag );
            }
        }
        return $a;
    }


    /**
     * Load tags with the starting prefix
     *
     * @param string $prefix The starting prefix of the tags.
     * @return array
     */
    function SelectWherePrefix( $prefix ) {
        global $CFG;

        $tags = recordset_to_array( get_recordset_sql(
            "SELECT tag, count(tag) as frequency FROM " . $CFG->prefix . "tags ".
            "WHERE left(tag, " . strlen($prefix) .
            ") = '$prefix' group by tag ORDER BY tag LIMIT 6" ) );

        $a = array();

        if( !!$tags ) {
            foreach( $tags as $tag ) {

                $t = new folio_tag( $tag );
                $t->count = $tag->frequency;
                $a[] = $t;
            }
        }
        return $a;
    }


    /**
     * Update the tags for the page.
     * HTML POST needs to be generated by editHtml() function.
     * Assumes data is already cleansed
     *
     * @param folio_page $page Page to update.
     * @param string $tagstring A string of tags separated by commas.
     * @return boolean
     */
    public function Update( folio_page $page, $tagstring ) {

        $tags = trim($tagstring);

        if( !isset( $page ) OR $page == false )
            trigger_error('Invalid page send to tags.update', E_USER_ERROR);

        delete_records('tags','tagtype','page','ref',$page->page_ident);
        insert_tags_from_string ($tags, 'page', $page->page_ident, 'public', $page->user_ident);

        // Return true to show success.
        return true;
    }


//////////////////
//              //
//  HTML Layer  //
//              //
//////////////////

    /**
     * Turn an array of tags into a single string
     *
     * @param array $tags An array of tags.
     * @return string
     */
    function toString( $tags ) {

        $t = array();

        if ( is_array( $tags ) ) {
            foreach ( $tags as $tag ) {
                $t[] = $tag->tag;
            }
            $tags = implode( ', ', $t );
        } else {
            // No tags
            $tags = '';
        }

        return $tags;
    }

}

?>
